<template>
    <show-modal :title="title" :loading="loading" width="800px" @cancel="cancel" :isSure="!isDisabled" @submit="submit">
        <a-form-model ref="form" :model="form" :rules="rules" v-bind="layout">
            <a-row :gutter="16">
                <a-col class="col_item" span="14">
                    <a-form-model-item label="工单名称" prop="orderName">
                        <a-input v-model.trim="form.orderName" :disabled="isDisabled" placeholder="请填写工单名称"/>
                    </a-form-model-item>
                </a-col>
                <a-col class="col_item" span="10">
                    <a-form-model-item label="工单类型" prop="orderType">
                        <a-select v-model="form.orderType" :disabled="isDisabled || nodeList.length?true:false" showSearch placeholder="请选择工单类型">
                            <a-select-option :value="item.value" v-for="item in workOrderTypes" :key="item.value">{{item.name}}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                </a-col>
                <a-col class="col_item" span="14">
                    <a-form-model-item label="接单部门" prop="deptId">
                        <a-tree-select
                            v-model="form.deptId"
                            :disabled="isDisabled"
                            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                            :tree-data="deptList"
                            :replaceFields="{children:'children',
                            title:'deptName',
                            key:'deptId',
                            value: 'deptId' }"
                            placeholder="请选择接单部门"
                        >
                        </a-tree-select>
                    </a-form-model-item>
                </a-col>
                <!-- <a-col class="col_item" span="10">
                    <a-form-model-item label="负责人" prop="leaderId">
                        <a-select
                            :disabled="isDisabled"
                            v-model="form.leaderId"
                            class="form_item"
                            show-search
                            option-filter-prop="children"
                            :filter-option="filterOption"
                            mode="multiple"
                            allowClear
                            placeholder="请选择负责人">
                            <a-select-option :value="item.userId+''" v-for="item in userList" :key="item.userId">{{item.userName}}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                </a-col> -->
                <template v-if="form.orderType=='B'">
                    <a-col class="col_item" span="10">
                        <a-form-model-item label="执行时间" prop="times">
                            <a-range-picker
                                :disabled="isDisabled"
                                style="width:100%;"
                                v-model="form.times"
                                :disabled-date="disabledDate"
                                :show-time="{ format: 'HH:mm:ss' }"
                                valueFormat="YYYY-MM-DD HH:mm:ss"
                                :placeholder="['开始时间', '结束时间']"/>
                        </a-form-model-item>
                    </a-col>
                    <a-col class="col_item" span="14">
                        <a-form-model-item label="延期扣分" prop="deduction">
                            <a-input-number placeholder="请输入延期扣分" :precision="1" :min="0" :step="1" :disabled="isDisabled" class="form_item" v-model="form.deduction" />
                            <!-- <p class="tip_number">只可输入整数</p> -->
                        </a-form-model-item>
                    </a-col>
                </template>
                <a-col class="col_item" span="10">
                    <a-form-model-item label="工单说明" prop="comments">
                        <a-textarea placeholder="请输入工单说明" :disabled="isDisabled" :max-length="200" v-model="form.comments" />
                    </a-form-model-item>
                </a-col>
                <!-- <a-col class="col_item" span="10" v-if="form.orderType=='A'">
                    <a-form-model-item label="每月执行" prop="isCycle">
                        <a-switch :disabled="isDisabled || nodeList.length?true:false" :checked="form.isCycle == 'Y' ? true : false" checked-children="是" un-checked-children="否" @change="onChangeShow" />
                    </a-form-model-item>
                </a-col> -->
                
            </a-row>
            <div class="order_process">
                <h3 class="title">工单流程</h3>
                <div class="time_line_box">
                    <a-timeline class="time_line">
                        <a-timeline-item v-for="(node,index) in nodeList" :key="node.id">
                            <div class="node_item">
                                <div class="node_side">
                                    <p class="name">{{node.nodeName}}</p>
                                    <p class="leader_name">{{node.leaderName}}</p>
                                    <!-- <a-tag color="green" v-if="node.status==='1'">已处理</a-tag>
                                    <a-tag color="blue" v-if="node.status==='0' && info.status!='return'">待处理</a-tag> -->
                                    <!-- <p class="mark" v-if="node.nodeMark">层级标签：<a-tag color="blue">{{node.nodeMark}}</a-tag></p> -->
                                </div>
                                <div class="node_control">
                                    <a-button v-if="form.status!='undo' && form.status" @click="addInfo(node,index)">查看</a-button>
                                    <template v-else>
                                        <a-button type="primary" class="btn_space" @click="addInfo(node,index)" :disabled="hasPerm(['sys:work:update'])">编辑</a-button>
                                        <a-button type="danger" v-if="index==(nodeList.length-1)" class="btn_space" @click="deleteNode(node,index)" :disabled="hasPerm(['sys:work:remove'])">删除</a-button>
                                    </template>
                                </div>
                            </div>
                            <a-divider />
                        </a-timeline-item>
                    </a-timeline>
                    <a-button type="primary" v-if="!form.status || form.status=='undo'" @click="addInfo()">添加新层级</a-button>
                </div>

            </div>
            <template v-if="isShow">
                <node-info :info="itemInfo" :orderId="form.id" :type="form.orderType" :isCycle="form.isCycle" :index="nodeIndex" :list="nodeList" :isDisabled="(!form.status || form.status=='undo')?false:true" :userList="userList" @cancel="isShow=false" @submit="addNode"/>
            </template>

        </a-form-model>
    </show-modal>
</template>

<script>
import { rules } from './rules';
const moment = require('moment');
import {workOrderTypes} from '../dictionary'
import {deepClone} from '@/utils'
import { insertOrderNode,updateOrderNode, updateWorkInfo,remoteQueryNodeList,deleteNodeInfo} from '@/api/workorder';
import nodeInfo from './node-info.vue';

export default {
    name: 'WorkInfo',
    components:{
        nodeInfo
    },
    props: {
        info: {
            type: Object,
            default: () => {}
        },
        userList:{
            type:Array,
            default:()=>[]
        },
        deptList:{
            type: Array,
            default: () => []
        },
        expandDept:{
            type:Array,
            default:()=>[]
        }
    },
    data() {
        return {
            loading: false,
            nodeLoading:false,
            rules,
            workOrderTypes,
            title: '工单信息',
            form:{
                orderName:'',
                orderType:undefined,
                times:[],
                score:0,
                deduction:0,
                startTime:'',
                endTime:'',
                deptId:undefined,
                deptName:'',
                // leaderId:[],
                // leaderName:[],
                type:"order",
                isCycle:'N'
            },
            layout: {
                labelCol: { span: 5 },
                wrapperCol: { span: 19 }
            },
            disabledDate(current) {
                return (current+24*60*60*1000) < moment().endOf('day');
            },
            nodeList:[],
            isShow:false,
            itemInfo:{},
            nodeIndex:''
        };
    },
    computed:{
        isDisabled(){
            return (!this.info.status || this.info.status=='undo')?false:true
        }
    },
    watch:{
        'form.deptId':function(e){
            let dept = this.expandDept.find(item=>item.deptId==e);
            this.form.deptName = dept.deptName;
        }
    },
    created(){
        this.form = {...this.form,...this.info};
        let {leaderId,startTime,endTime,} = this.info;
        this.getNodeList();
        if(leaderId){
            this.form.leaderId = leaderId.split(',')
        }
        if(startTime){
            this.form.times = [startTime,endTime]
        }
    },
    methods:{
        submit(isSumbit=true){
            this.$refs.form.validate(async valid => {
                if (valid) {
                    try {
                        let res = null;
                        this.loading = true;
                        let form = deepClone(this.form);
                        let nodeList = this.nodeList;
                        let {times,leaderId} = form;
                        let start = times[0]
                        let end = times[1]
                        if(form.orderType=='A'){
                            delete form.startTime;
                            delete form.endTime;
                        }else{
                            form.startTime = moment(start).format('YYYY-MM-DD HH:mm:ss');
                            form.endTime = moment(end).format('YYYY-MM-DD HH:mm:ss');
                        }
                        let leaderName = [];
                        // this.userList.map(user=>{
                        //     leaderId.map(leader=>{
                        //         if(user.userId==leader){
                        //             leaderName.push(user.userName)
                        //         }
                        //     })
                        // })
                        // form.leaderName = leaderName.join(',');
                        // form.leaderId = form.leaderId.join(',')
                        delete form.leaderName
                        delete form.leaderId
                        if(nodeList?.length){
                            nodeList.map((node,index)=>{
                                node.nodeSeq = index+1;
                            })
                        }
                        form.list = nodeList;
                        form.isCycle = 'N'
                        delete form.times;
                        if (form.id) {
                            res = await updateOrderNode(form);
                        } else {
                            res = await insertOrderNode(form);
                        }
                        this.$message.success('操作成功!');
                        this.$emit('submit');
                    } finally {
                        this.loading = false
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //切换状态
        onChangeShow(checked) {
            if (checked) {
                this.form.isCycle = 'Y';
            } else {
                this.form.isCycle = 'N';
            }
        },
        cancel(){
            this.$emit('cancel')
        },
        addNode(e){
            let {index} = e;
            let nodeLength = this.nodeList.length;
            if(index==nodeLength && index==0){
                this.nodeList.push(e);
            }else if(index<nodeLength){
                this.nodeList.splice(index,1,e);
            }else{
                this.nodeList.push(e);
            }
            // let nodeIndex = this.nodeList.findIndex(item=>item.nodeName==nodeName);
            // if(nodeIndex==-1){
            //     this.nodeList.push(e);
            // }else{
            //     this.nodeList.splice(nodeIndex,1,e);
            // }
            this.isShow =false;
        },
       
        async getNodeList(){
            let orderId = this.form.id || '';
            if(orderId){
                try{
                    this.nodeLoading = true;
                    let res = await remoteQueryNodeList({orderId,page:1,size:50});
                    let {list} = res.data;
                    this.nodeList = list;
                }finally{
                    this.nodeLoading = false;
                    this.isShow = false;
                }
            }
        },
        addInfo(info={},index=''){
            let orderTypes = ['A','B'];
            let isType = orderTypes.indexOf(this.form.orderType);
            if(isType==-1){
                this.$message.error('请选择工单类型!');
                return false;
            }
            this.itemInfo = info;
            this.isShow = true;
            if(info.nodeName){
                this.nodeIndex = index;
            }else{
                this.nodeIndex = this.nodeList.length
            }
        },
        deleteNode(item,index){
            this.$confirm({
                title: '提示',
                content: '确定要删除工单层级？',
                okText: '确定',
                cancelText: '取消',
                onOk:async ()=>{
                    try{
                        let {id} = item;
                        if(id){
                            let ids=[item.id];
                            await deleteNodeInfo({ids});
                        }
                        this.nodeList.splice(index,1)
                        this.$message.success('删除成功!');
                        // this.getNodeList(1);
                    }catch(err){

                    }
                },
                onCancel() {}
            });
        },
        filterOption(input, option) {
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
    }
}
</script>
<style lang="scss" scoped>
.order_process{
    margin: 0 20px;
    .title{
        font-size: 14px;
        color: #333;
    }
    .time_line_box{
        margin: 20px 0 0 50px;
        .node_item{
            display: flex;
            .node_side{
                width: 440px;
                flex-shrink: 0;
                .name{
                    font-size: 14px;
                    color: #333;
                    font-weight: 600;
                }
                .leader_name{
                    margin-bottom: 5px;
                    font-size: 13px;
                }
            }
            .node_control{
                // display: flex;
                flex: 1;
                text-align: right;
            }
        }
    }
}
</style>
